package com.tzinfo.tzt.fragment;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.tzinfo.tzt.R;
import com.tzinfo.tzt.activity.util.FragmentHomeListviewAdapter;
import com.tzinfo.tzt.activity.util.FragmentHomeListviewAdapter2;
import com.tzinfo.tzt.activity.util.FragmentHomeListviewAdapter3;
import com.tzinfo.tzt.util.HttpUtils;
import com.tzinfo.tzt.util.ResultMessage;
import com.tzinfo.tzt.util.Resultmap;


import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2014/11/12.
 */
public class MyFragment extends Fragment {
    int mNum;
    private PullToRefreshListView listView;
    private Context context;
    private TextView editText1;
    private Spinner spinner;
    private ImageView imageView;
    private LinearLayout carplateserachbar;
    int pagesize = 5;
    int page;
    List<Resultmap> listData;
    private FragmentHomeListviewAdapter fragmentHomeListviewAdapter;


    public static MyFragment newInstance(int position) {
        MyFragment fragment = new MyFragment();
        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putInt("num", position);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        context = activity;
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //这里我只是简单的用num区别标签，其实具体应用中可以使用真实的fragment对象来作为叶片
        mNum = getArguments() != null ? getArguments().getInt("num") : 1;
        page = 1;

    }

    /**
     * 为Fragment加载布局时调用*
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_pager_list, null);
        spinner = (Spinner) view.findViewById(R.id.carplateserachbar_spinner);
        imageView = (ImageView) view.findViewById(R.id.carplateserachbar_imageView);
        editText1 = (EditText) view.findViewById(R.id.carplateserachbar_et);
        carplateserachbar = (LinearLayout) view.findViewById(R.id.home_carplateserachbar);

        listView = (PullToRefreshListView) view.findViewById(R.id.fragment__home_pager_listView);


        setCurrentItem(mNum);

        return view;
    }

    public class GetData extends AsyncTask<String, Void, ResultMessage> {
        @Override
        protected ResultMessage doInBackground(String... params) {
            ResultMessage result;
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            pairs.add(new BasicNameValuePair("areaid", "1"));
            //   pairs.add(new BasicNameValuePair("Title", ""));
            pairs.add(new BasicNameValuePair("page", String.valueOf(page)));
            pairs.add(new BasicNameValuePair("pagesize", String.valueOf(pagesize)));
            String GetDataUrl = "http://auto.tzinfo.net/mob/api/Car4SList.ashx";
            String loginResultString = HttpUtils.doPostMethod(GetDataUrl, pairs);
            Gson gson = new Gson();
            result = gson.fromJson(loginResultString, ResultMessage.class);
            return result;
        }

        @Override
        protected void onPostExecute(ResultMessage result) {
            super.onPostExecute(result);
            if (result.getSuccess() == true) {
                if (listData == null) {
                    listData = result.getData();
                } else {
                    listData.addAll(result.getData());
                    fragmentHomeListviewAdapter.notifyDataSetChanged();
                }
                fragmentHomeListviewAdapter = new FragmentHomeListviewAdapter(context, listData);
                fragmentHomeListviewAdapter.notifyDataSetChanged();
                listView.setAdapter(fragmentHomeListviewAdapter);
                listView.onRefreshComplete();
            } else {
                Toast.makeText(context, result.getErrorMsg(), Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }

    public class GetData2 extends AsyncTask<String, Void, ResultMessage> {

        @Override
        protected ResultMessage doInBackground(String... params) {
            ResultMessage result;
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            pairs.add(new BasicNameValuePair("areaid", "1"));
            //   pairs.add(new BasicNameValuePair("Title", ""));
            pairs.add(new BasicNameValuePair("page", "1"));
            pairs.add(new BasicNameValuePair("pagesize", "4"));
            String GetDataUrl = "http://auto.tzinfo.net/mob/api/newsList.ashx";
            String loginResultString = HttpUtils.doPostMethod(GetDataUrl, pairs);

            Gson gson = new Gson();
            result = gson.fromJson(loginResultString, ResultMessage.class);
            return result;
        }

        @Override
        protected void onPostExecute(ResultMessage result) {
            super.onPostExecute(result);
            if (result.getSuccess() == true) {

                listView.setAdapter(new FragmentHomeListviewAdapter2(context, result.getData()));
            } else {
                Toast.makeText(context, result.getErrorMsg() + "操", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }

    public class GetData3 extends AsyncTask<String, Void, ResultMessage> {

        @Override
        protected ResultMessage doInBackground(String... params) {
            ResultMessage result;
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            pairs.add(new BasicNameValuePair("areaid", "1"));
            //   pairs.add(new BasicNameValuePair("Title", ""));
            pairs.add(new BasicNameValuePair("page", "1"));
            pairs.add(new BasicNameValuePair("pagesize", "3"));
            String GetDataUrl = "http://auto.tzinfo.net/mob/api/Car4SList.ashx";
            String loginResultString = HttpUtils.doPostMethod(GetDataUrl, pairs);

            Gson gson = new Gson();
            result = gson.fromJson(loginResultString, ResultMessage.class);
            return result;
        }

        @Override
        protected void onPostExecute(ResultMessage result) {
            super.onPostExecute(result);
            if (result.getSuccess() == true) {

                listView.setAdapter(new FragmentHomeListviewAdapter3(context, result.getData()));
            } else {
                Toast.makeText(context, result.getErrorMsg() + "操", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }

    public class GetDataa extends AsyncTask<String, Void, ResultMessage> {

        @Override
        protected ResultMessage doInBackground(String... params) {
            ResultMessage result;
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            pairs.add(new BasicNameValuePair("areaid", "1"));
            //   pairs.add(new BasicNameValuePair("Title", ""));
            pairs.add(new BasicNameValuePair("page", "1"));
            pairs.add(new BasicNameValuePair("pagesize", "6"));
            pairs.add(new BasicNameValuePair("Title", editText1.getText().toString()));
            String GetDataUrl = "http://auto.tzinfo.net/mob/api/Car4SList.ashx";
            String loginResultString = HttpUtils.doPostMethod(GetDataUrl, pairs);

            Gson gson = new Gson();
            result = gson.fromJson(loginResultString, ResultMessage.class);
            return result;
        }

        @Override
        protected void onPostExecute(ResultMessage result) {
            super.onPostExecute(result);
            if (result.getSuccess() == true) {

                listView.setAdapter(new FragmentHomeListviewAdapter(context, result.getData()));
            } else {
                Toast.makeText(context, result.getErrorMsg() + "操", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }

    public class UPData extends AsyncTask<String, Void, ResultMessage> {

        @Override
        protected ResultMessage doInBackground(String... params) {
            ResultMessage result;
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            pairs.add(new BasicNameValuePair("areaid", "1"));
            //   pairs.add(new BasicNameValuePair("Title", ""));
            pairs.add(new BasicNameValuePair("page", String.valueOf(page)));
            pairs.add(new BasicNameValuePair("pagesize", String.valueOf(pagesize)));
            page++;
            String GetDataUrl = "http://auto.tzinfo.net/mob/api/Car4SList.ashx";
            String loginResultString = HttpUtils.doPostMethod(GetDataUrl, pairs);

            Gson gson = new Gson();
            result = gson.fromJson(loginResultString, ResultMessage.class);
            return result;
        }

        @Override
        protected void onPostExecute(ResultMessage result) {
            super.onPostExecute(result);
            if (result.getSuccess() == true) {
                listData.addAll(result.getData());
                fragmentHomeListviewAdapter.notifyDataSetChanged();
                listView.onRefreshComplete();
            } else {
                Toast.makeText(context, result.getErrorMsg(), Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }

    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() == 0) {
//                GetDataa aa = new GetDataa();
//                aa.execute();
            }

        }
    };

    private void setCurrentItem(int checkId) {
        switch (mNum) {
            case 0:
                carplateserachbar.setVisibility(View.VISIBLE);
                spinner.setVisibility(View.VISIBLE);
                imageView.setVisibility(View.GONE);
                editText1.addTextChangedListener(textWatcher);
                GetData a = new GetData();
                a.execute();
                listView.setMode(PullToRefreshBase.Mode.BOTH);
                listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
                    @Override
                    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                        String label = DateUtils.formatDateTime(
                                context,
                                System.currentTimeMillis(),
                                DateUtils.FORMAT_SHOW_TIME
                                        | DateUtils.FORMAT_SHOW_DATE
                                        | DateUtils.FORMAT_ABBREV_ALL);
                        // 显示最后更新的时间
                        refreshView.getLoadingLayoutProxy()
                                .setLastUpdatedLabel(label);
                        new GetData().execute();
                    }

                    @Override
                    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                        String label = DateUtils.formatDateTime(
                                context,
                                System.currentTimeMillis(),
                                DateUtils.FORMAT_SHOW_TIME
                                        | DateUtils.FORMAT_SHOW_DATE
                                        | DateUtils.FORMAT_ABBREV_ALL);
                        // 显示最后更新的时间
                        refreshView.getLoadingLayoutProxy()
                                .setLastUpdatedLabel(label);
                        new UPData().execute();
                    }
                });

                editText1.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                        GetDataa aa = new GetDataa();
                        aa.execute();
                        return true;
                    }
                });
                break;
            case 1:
                carplateserachbar.setVisibility(View.VISIBLE);
                spinner.setVisibility(View.GONE);
                imageView.setVisibility(View.VISIBLE);
                GetData2 b = new GetData2();
                b.execute();
                break;


            case 2:
                carplateserachbar.setVisibility(View.GONE);

                GetData3 c = new GetData3();
                c.execute();
                break;
            default:
                break;
        }

    }
}
